package hos.view

import android.os.Build
import android.view.View
import java.util.concurrent.atomic.AtomicInteger

/**
 * <p>Title: ViewUtils </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2024-08-12 13:28
 * @version : 1.0
 */
object ViewUtils {

    private val sNextGeneratedId by lazy {
        AtomicInteger(1)
    }

    @JvmStatic
    fun generateViewId(): Int {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return View.generateViewId()
        } else {
            while (true) {
                val result: Int = sNextGeneratedId.get()
                // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
                var newValue = result + 1
                if (newValue > 0x00FFFFFF) newValue = 1 // Roll over to 1, not 0.

                if (sNextGeneratedId.compareAndSet(result, newValue)) {
                    return result
                }
            }
        }
    }

    fun forTarget(block: View.() -> Unit, vararg views: View) {
        if (views.isEmpty()) {
            return
        }
        views.forEach {
            block(it)
        }
    }
}